import pyautogui
import screenshot
import urllib3
import cv
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.webdriver.edge.service import Service
from selenium.common.exceptions import NoSuchElementException

SONGHUA = 1
YIMIAOMIAO = 2
YOUKE = 3

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# 存储为列表嵌套字典格式，方便提取
account_list = [

    {"account": "13125453021", "password": "LiangRH040409"},
    {"account": "18355171839", "password": "lhb111466"},
    {"account": "18802498172", "password": "gyj041010"},
    {"account": "15309435349", "password": "yzd@laoda"},
    {"account": "18143574484", "password": "2820447980wxp"},
    {"account": "16692782078", "password": "20040324cjn"},
    {"account": "18187277656", "password": "Hyd9cnhnjj"},
    {"account": "15141359899", "password": "20040916Cjh"},
    {"account": "18004230380", "password": "q20040322"},
    {"account": "15193928117", "password": "asdfghjkl111"},
    {"account": "13889871219", "password": "QAQ.811219"},
    {"account": "13332314426", "password": "zy2004426"},
    {"account": "17038449739", "password": "zq1996526"},
    {"account": "18842547749", "password": "yiban666.."},
    {"account": "13504065723", "password": "jpj021123"},
    {"account": "13072432730", "password": "@Lxb20040508"},
    {"account": "15809883409", "password": "lx999325"},
    {"account": "13940556429", "password": "yll147258369"},
    {"account": "19944083220", "password": "lty200307140053@"},
    {"account": "18593731447", "password": "grh200311"},
    {"account": "13332197197", "password": "224624@sxt"},
    {"account": "13969999436", "password": "cat306e2lu"},
    {"account": "18641533217", "password": "12345678aA"},
    {"account": "13147844556", "password": "040609yxf"},
    {"account": "13704287985", "password": "wcjm23333"},
    {"account": "18101062162", "password": "dingwei3617"},
    {"account": "18793262987", "password": "mhcymbrags123"},

    {"account": "18240608548", "password": "W20040903ml"},
    {"account": "13030779159", "password": "zsq2090582258"},
    {"account": "18009809814", "password": "qwerlol1314"},
    {"account": "19931493905", "password": "lxc19931493905"},
    {"account": "17362114241", "password": "wangyongqi0406"},
    {"account": "13080831073", "password": "123wuyubo"},
    {"account": "15184264366", "password": "LIUSHUAI666"},
    {"account": "13841064609", "password": "m20040601"},
    {"account": "18794373989", "password": "qy8617900"},
    {"account": "18104185385", "password": "Shiji8888!"},
    {"account": "18941951400", "password": "bjh711826"},
    {"account": "15998316797", "password": "hsh10086352515"},
    {"account": "15242588146", "password": "20040730Hjg"},
    {"account": "15514397019", "password": "qwerty1234"},
    {"account": "15141130969", "password": "qiaofufu000"},
    {"account": "18309817910", "password": "Hjr158158"},
    {"account": "15541094751", "password": "LY123456"},
    {"account": "15842281140", "password": "20030902dyxin"},
    {"account": "17741139080", "password": "yiban666@123456"},
    {"account": "19893553682", "password": "lanyangyang110"},
    {"account": "15649538433", "password": "zjc200306."},
    {"account": "18240218687", "password": "W20415479"},
    {"account": "15893219680", "password": "hxwhly2."},
    {"account": "18802498070", "password": "lmy20031017*"},
    {"account": "15883319324", "password": "20haohjx*"},
    {"account": "13154270208", "password": "banhan112233"},
    {"account": "17364633529", "password": "sau307666"},
    {"account": "18541008407", "password": "ab151515"},
    {"account": "15559870908", "password": "Ljl5201314..."},
    {"account": "15542093955", "password": "lxy123456"},
    {"account": "13393731190", "password": "Sby0.123"},
    {"account": "15117436668", "password": "04011975gn"},
    {"account": "13358947922", "password": "chentao0926."},
    {"account": "13514283038", "password": "XZQWFY1714"},
    {"account": "15093991914", "password": "wasd1234..."},
    {"account": "15512712782", "password": "Canlanshiguang0"},
    {"account": "19899252317", "password": "ZLQ314217zlq"},
    {"account": "18109429766", "password": "nx2529213760"},
    {"account": "18892479377", "password": "yll20040316"},
    {"account": "15842117192", "password": "abclhj1324576890"},
    {"account": "15164151168", "password": "q123456789"},
    {"account": "18861385089", "password": "20040707xxb!"},
    {"account": "19551267713", "password": "hzh1314520"},
    {"account": "19813536083", "password": "GHTSNWY5201314"},
    {"account": "18671931208", "password": "120191031.sxj"},
    {"account": "19955069050", "password": "120684abcd"},
    {"account": "18342419747", "password": "588598Fu"},
    {"account": "18540312479", "password": "202319twsT@"},
    {"account": "15391984282", "password": "1234567890dys"},
    {"account": "13941488239", "password": "4321QWER"},
    {"account": "15842224578", "password": "yunliwuli.."},
    {"account": "15940665151", "password": "20040921sywsyw"},
    {"account": "15940653147", "password": "040319QAZxsw!"},
    {"account": "15841692835", "password": "why20040328"},
    {"account": "18294255156", "password": "gjt20030518"},
    {"account": "18841462500", "password": "whx@123456"},
    {"account": "13065392106", "password": "1593572580q"},
    {"account": "15241627363", "password": "daiyuguo."},
    {"account": "18842739715", "password": "@XXGMCXZR123"},
    {"account": "15898444720", "password": "961031377xhf"},
    {"account": "13942410278", "password": "p860907846"},
    {"account": "18840611628", "password": "fulin081699"},
    {"account": "18624473193", "password": "jixinyu0207.."},
    {"account": "15660015952", "password": "123456asd"},
    {"account": "17352115499", "password": "528600Bm"},
    {"account": "15840313615", "password": "WS122600"},
    {"account": "13654268922", "password": "20040928zcx"},
    {"account": "15941756395", "password": "699025tonghuan"},
    {"account": "15734150792", "password": "15734150792Wy."},
    {"account": "18802499410", "password": "wjx109722"},
    {"account": "13019383150", "password": "yynb0526"},
    {"account": "15693465298", "password": "hanyanyan1011"},
    {"account": "18546105663", "password": "xiesiming0.0"},
    {"account": "13969989533", "password": "LMY12138"},
    {"account": "15308687323", "password": "3114425and"},
    {"account": "18842154113", "password": "Lyx18842154113"},
    {"account": "15204076043", "password": "Kllcpx521."},
    {"account": "19339810907", "password": "19339810907lwj "},
    {"account": "13604958027", "password": "cjx20040803"},
    {"account": "18512429098", "password": "safety120"},
    {"account": "13668245196", "password": "1008611zyx"},
    {"account": "15640642747", "password": "zhangyuya1125"},
    {"account": "15642853098", "password": "dy3993859"},
    {"account": "15187219324", "password": "BLEACH2381naruto"},
    {"account": "13885377436", "password": "qazxft5plmnhy"},
    {"account": "13881146746", "password": "lsl200414666"},
    {"account": "18340720068", "password": "jhy426909"},
    {"account": "15114103125", "password": "3.14liang"},
    {"account": "13352199882", "password": "mengfansen1635"},
    {"account": "19993295027", "password": "wy102557"},
    {"account": "13188230938", "password": "@yiban608844"},
    {"account": "18893260634", "password": "Ly223401010233"},
    {"account": "15097061109", "password": "lyy003119"},
    {"account": "15141648458", "password": "Y20040131"},
    {"account": "15774870176", "password": "leiying1314"},
    {"account": "13784261211", "password": "1378426Hh"},
    {"account": "18802498025", "password": "050410ljm"},
    {"account": "13898641405", "password": "hpk2180772632"},
    {"account": "18154529306", "password": "yy223401050135"},
    {"account": "15804052068", "password": "15804052068lsq"},
    {"account": "17757842268", "password": "DzQ8J46N@6"},
    {"account": "18085341428", "password": "LJD.297643"},
    {"account": "13898524850", "password": "Asd041226"},
    {"account": "13889775319", "password": "abk52134"},
    {"account": "17727864592", "password": "Jzlzs6.."},
    {"account": "13998456679", "password": "13998456679sjr"},
    {"account": "15643216555", "password": "hay041207"},
    {"account": "15141082198", "password": "qpzm13795"},
    {"account": "15566456468", "password": "z9342492644826w"},
    {"account": "15104104117", "password": "a3132640959"},
    {"account": "17640036638", "password": "qtc20050206"},
    {"account": "18219933967", "password": "991028ab"},
    {"account": "13614064065", "password": "lj515515"},
    {"account": "13149795458", "password": "20040710s"},
    {"account": "18204280563", "password": "syn18204280563"},
    {"account": "15537588731", "password": "zsz15537588731"},
    {"account": "13898437371", "password": "dmy20040524"},
    {"account": "13324277103", "password": "ljy123123!"},
    {"account": "18393535742", "password": "43162sbwl663519"},
    {"account": "18309816046", "password": "AAA111111"},
    {"account": "15716638389", "password": "zyx76691"},
    {"account": "13704620586", "password": "zh200304190013"},
    {"account": "18204190985", "password": "yyh629514"},
    {"account": "15725936619", "password": "Wang148632597"},
    {"account": "15041703362", "password": "Gjh20041202"},
    {"account": "18712390558", "password": "kyx20040902"},
    {"account": "18239086956", "password": "wzl223401010420"},
]
path = r"D:\webdriver\edgedriver_win641\msedgedriver.exe"
service = Service(executable_path=path)


def is_login_successful(driver):
    try:
        # 尝试查找错误提示元素
        error_element = driver.find_element(By.CSS_SELECTOR, "p.error.js-error")

        # 如果找到元素，检查其文本内容是否匹配
        if "用户名或密码错误" in error_element.text:
            return False  # 登录失败
        return True  # 有该元素但文本不匹配，视为登录成功
    except NoSuchElementException:
        # 未找到错误元素，视为登录成功
        return True


def click_leftmost_shape(color, is_yoke=False):
    screenshot.capture_screen_region(1020, 640, 1520, 1040, "captured_region.png")
    x, y = cv.find_leftmost_shape("captured_region.png", is_yoke, color=color)
    pyautogui.moveTo(x, y)
    pyautogui.click()


def login(driver, username, password):
    WebDriverWait(driver, 4).until(
        EC.presence_of_element_located((By.ID, "account-txt"))  # 等待账号输入框出现
    )
    last_url = driver.current_url
    account_element = driver.find_element(By.ID, "account-txt")
    account_element.clear()
    account_element.send_keys(username)
    password_element = driver.find_element(By.ID, "password-txt")
    password_element.clear()
    password_element.send_keys(password)
    login_button = driver.find_element(By.ID, "login-btn")
    login_button.click()
    # 替换time.sleep(1.5)为显式等待
    WebDriverWait(driver, 20).until(
        EC.presence_of_element_located((By.CLASS_NAME, "shumei_captcha_slide_tips"))  # 等待验证码提示出现
    )
    while 1:
        prompt = driver.find_element(By.CLASS_NAME, "shumei_captcha_slide_tips")
        text = prompt.text
        if len(text) >= 7:
            color_text = text[7]
        else:
            color_text = "红"
        if color_text == "红":
            color = "red"
        elif color_text == "蓝":
            color = "blue"
        elif color_text == "绿":
            color = "green"
        elif color_text == "黄":
            color = "yellow"
        else:
            color = "red"
        click_leftmost_shape(color)
        if driver.current_url == last_url:
            time.sleep(1.5)
        if driver.current_url != last_url:
            print("验证成功")
            return True
        if not is_login_successful(driver):
            print("登录失败")
            return False


def auto_scripts(url, type, list):
    run_count = 0
    success_count = 0
    for i in list:
        username = i["account"]
        password = i["password"]
        # 1,送花；2，易喵喵；3，优课
        if type == 1:
            if send_flowers(url, username, password):
                success_count = success_count + 1
            else:
                print("第", run_count, "个账号密码错误")
        elif type == 2:
            if YiMiaoMiao(url, username, password):
                success_count = success_count + 1
            else:
                print("第", run_count, "个账号密码错误")
        elif type == 3:
            if YouKe(url, username, password, "AAAAA"):
                success_count = success_count + 1
            else:
                print("第", run_count, "个账号密码错误")
        elif type == 4:
            if YouKe_jiaru(url, username, password):
                success_count = success_count + 1
            else:
                print("第", run_count, "个账号密码错误")
        run_count = run_count + 1
        print("已经运行", run_count, "次", "\n", "成功", success_count, "次")


def YoKe_login(driver, username, password):
    wait = WebDriverWait(driver, 10)
    # 有多个类时用.隔开，而不是使用空格
    inputs = wait.until(
        EC.presence_of_all_elements_located((By.CLASS_NAME, "input-control.newUI-input")))
    inputs[0].send_keys(username)
    inputs[1].send_keys(password)
    submit = driver.find_element(By.ID, "yooc_submit")
    submit.click()
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.CLASS_NAME, "shumei_captcha_slide_tips"))  # 等待验证码提示出现
    )
    last_url = driver.current_url
    while 1:
        if driver.current_url != last_url:
            print("验证成功")
            return True
        prompt = driver.find_element(By.CLASS_NAME, "shumei_captcha_slide_tips")
        text = prompt.text
        color_texts = ["红", "黄", "蓝", "绿"]
        if len(text) > 8 and text[7] in color_texts:
            color_text = text[7]
            print(text)
        elif text == "图片加载中..." or text == "验证失败,请重新验证":
            time.sleep(0.5)
            continue
        else:
            time.sleep(0.5)
            continue
        if color_text == "红":
            color = "red"
        elif color_text == "蓝":
            color = "blue"
        elif color_text == "绿":
            color = "green"
        elif color_text == "黄":
            color = "yellow"
        else:
            color = "red"
        click_leftmost_shape(color, True)
        time.sleep(1)
        if driver.current_url == last_url:  # url变了说明跳转成功
            time.sleep(0.5)
        else:
            print("验证成功")
            return True
        if not YoKe_is_login_successful(driver):
            print("登录失败")
            return False


def YoKe_is_login_successful(driver):
    try:
        # 尝试查找错误提示元素
        error_element = driver.find_element(By.CSS_SELECTOR, "p.error.js-error")

        # 如果找到元素，检查其文本内容是否匹配
        if "用户名或密码错误" in error_element.text:
            return False  # 登录失败
        return True  # 有该元素但文本不匹配，视为登录成功
    except NoSuchElementException:
        # 未找到错误元素，视为登录成功
        return True


def YouKe(url, username, password, answer_sequence):
    driver = webdriver.Edge(service=service)
    driver.get(url)
    driver.maximize_window()
    driver.execute_script("window.scrollTo(0, 0);")
    vote = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '//a[@title="课群投票"]'))
    )
    vote.click()
    enter_vote = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CLASS_NAME, "member_required"))
    )
    enter_vote.click()
    # “课程投票”按钮
    # login_btn = WebDriverWait(driver, 10).until(
    #   EC.element_to_be_clickable((By.XPATH, "/html/body/header/div/div[2]/a[1]")))
    # login_btn.click()
    if not YoKe_login(driver, username, password):
        driver.quit()
        return False
    vote = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, '//a[@title="课群投票"]'))
    )
    vote.click()
    # a标签“进入投票”按钮
    enter_vote = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CLASS_NAME, "member_required"))
    )
    enter_vote.click()
    # 在弹出的输入邀请码处加入url等号后的部分
    input_element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "dlgc-2"))
    )
    # 找到等号的位置
    equal_index = url.find('=')
    # 提取等号后的字符
    result = url[equal_index + 1:]
    time.sleep(0.5)
    input_element.send_keys(result)
    ok = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "dlgc-3"))
    )
    ok.click()
    time.sleep(0.5)
    enter_vote_ = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CLASS_NAME, "member_required"))
    )
    enter_vote_.click()
    questions = WebDriverWait(driver, 10).until(
        EC.presence_of_all_elements_located((By.CLASS_NAME, "question"))
    )
    print(len(questions))
    # 遍历每个问题并选择答案
    for i, question in enumerate(questions):
        # 获取当前问题的答案字符
        answer_char = answer_sequence[i].upper() if i < len(answer_sequence) else 'A'
        # 计算选项索引 (A=0, B=1, C=2, D=3)
        option_index = ord(answer_char) - ord('A')
        # 在问题元素内查找所有选项
        options = WebDriverWait(question, 5).until(
            EC.presence_of_all_elements_located((By.CLASS_NAME, "option"))
        )
        # 验证选项索引是否有效
        if option_index < 0 or option_index >= len(options):
            print(f"问题 {i + 1}: 无效的答案字符 '{answer_char}'，跳过")
            continue
        # 获取目标选项
        target_option = options[option_index]
        # 等待选项可点击
        WebDriverWait(driver, 5).until(
            EC.element_to_be_clickable(target_option)
        )
        # 滚动到选项位置
        driver.execute_script("arguments[0].scrollIntoView({behavior: 'smooth', block: 'center'});", target_option)
        # 点击选项
        target_option.click()
        print(f"问题 {i + 1}: 成功选择选项 {answer_char}")
        # 可选：等待选项被选中（适用于单选按钮）
    ok_ = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.ID, "survey-submit-122797"))
    )
    ok_.click()
    driver.quit()
    return True


def YouKe_jiaru(url, username, password):
    driver = webdriver.Edge(service=service)
    driver.get(url)
    driver.maximize_window()
    driver.execute_script("window.scrollTo(0, 0);")
    vote = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CLASS_NAME, 'kq-join'))
    )
    vote.click()
    if not YoKe_login(driver, username, password):
        driver.quit()
        return False
    vote = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.CLASS_NAME, 'kq-join'))
    )
    vote.click()
    # “课程投票”按钮
    # login_btn = WebDriverWait(driver, 10).until(
    #   EC.element_to_be_clickable((By.XPATH, "/html/body/header/div/div[2]/a[1]")))
    # login_btn.click()
    # 在弹出的输入邀请码处加入url等号后的部分
    input_element = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "dlgc-2"))
    )
    # 找到等号的位置
    equal_index = url.find('=')
    # 提取等号后的字符
    result = url[equal_index + 1:]
    time.sleep(0.5)
    input_element.send_keys(result)
    ok = WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "dlgc-3"))
    )
    ok.click()
    driver.quit()
    return True


def YiMiaoMiao(url, username, password):
    driver = webdriver.Edge(service=service)
    driver.get(url)
    driver.maximize_window()
    driver.execute_script("window.scrollTo(0, 0);")
    wait = WebDriverWait(driver, 10)
    # 找到最下方的“svg-icon”类，就是心形按钮
    all_svg_icons = wait.until(
        EC.presence_of_all_elements_located((By.CLASS_NAME, "svg-icon"))

    )

    svg_element = None
    for svg in all_svg_icons:
        svg_element = svg
    svg_element.click()
    ok_element = WebDriverWait(driver, 10).until(
        EC.element_to_be_clickable((By.XPATH, "/html/body/div/div[2]/div[3]/a[2]"))
    )
    # 点击确定
    ok_element.click()
    if not login(driver, username, password):
        driver.quit()
        return False
    wait = WebDriverWait(driver, 10)
    like_button = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.btn.like")))
    svg_icon = like_button.find_element(By.CSS_SELECTOR, "svg.svg-icon")
    # 若类型是“liked”说明已经点赞，不要点击，否则会取消。
    is_liked = "liked" in svg_icon.get_attribute("class")
    if not is_liked:
        svg_icon.click()
        print("点赞成功")
    else:
        print("已经点赞")
    driver.quit()
    return True


def send_flowers(url, username, password):
    driver = webdriver.Edge(service=service)
    driver.get(url)
    driver.maximize_window()
    # 替换time.sleep(4)为显式等待
    if not login(driver, username, password):
        driver.quit()
        return False
    WebDriverWait(driver, 10).until(
        EC.presence_of_element_located((By.ID, "appZan"))
    )
    app_zan = driver.find_element(By.ID, "appZan")
    class_attr = app_zan.get_attribute("class")
    is_disabled = "disable" in class_attr
    num_flowers = driver.find_element(By.XPATH, "/html/body/div[3]/span")
    num = num_flowers.text
    if not is_disabled:
        app_zan.click()
        print("送花成功,当前花的数量为", num, "\n")
    else:
        print("已送过花,当前花的数量为", num, "\n")
    driver.quit()
    return True


url = r"https://q.yiban.cn/app/index/appid/1956677#block2"
auto_scripts(url, SONGHUA, account_list)
